package com.cg.common;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.io.UnsupportedEncodingException;
import java.util.Date;
public class JWTUtils {
        private static final long EXPIRE_TIME = 1 * 60 * 1000; // 过期时间（15分钟）
        private static final String TOKEN_SECRET = "f26e587c28064d0e855e72c0a6a0e618"; // 密钥
        //将账号和密码弄成token
        public static String sign(String account, String password) throws UnsupportedEncodingException {
            return JWT.create()
                    .withClaim("account", account)
                    .withClaim("password", password)
                    .withExpiresAt(new Date(System.currentTimeMillis() + EXPIRE_TIME))
                    .sign(Algorithm.HMAC256(TOKEN_SECRET));
        }
        public static boolean verify(String token) {
            try {
                JWT.require(Algorithm.HMAC256(TOKEN_SECRET)).build().verify(token);
                return true;
            } catch (Exception exception) {
                return false;
            }
        }

        public static String getAccount(String token) {
            try {
                DecodedJWT jwt = JWT.decode(token);
                return jwt.getClaim("account").asString();
            } catch (JWTDecodeException exception) {
                return null;
            }
        }
        public static String getPassword(String token) {
            try {
                DecodedJWT jwt = JWT.decode(token);
                return jwt.getClaim("password").asString();
            } catch (JWTDecodeException exception) {
                return null;
            }
        }

}

